﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure.StorageClient;
using System.Net;

namespace DBLOG.Azure.VirtualPathProvider
{
    public static class ExtensionMethods
    {
        /// <summary>
        /// Used to get subdirectories
        /// </summary>
        /// <param name="directory">The directory for which to query for subdirectories</param>
        /// <returns></returns>
        public static List<CloudBlobDirectory> GetSubdirectories(this CloudBlobDirectory directory)
        {
            List<CloudBlobDirectory> directories = new List<CloudBlobDirectory>();

            var blobs = directory.ListBlobs();

            foreach (var dir in blobs.OfType<CloudBlobDirectory>())
            {
                directories.Add(dir);
            }

            return directories;
        }

        /// <summary>
        /// Used to get files in a directory
        /// </summary>
        /// <param name="directory">The directory for which to query for files</param>
        public static List<CloudBlob> GetFiles(this CloudBlobDirectory directory)
        {
            List<CloudBlob> files = new List<CloudBlob>();

            var blobs = directory.ListBlobs();

            foreach (var file in blobs.OfType<CloudBlob>())
            {
                files.Add(file);
            }

            return files;
        }

        /// <summary>
        /// Used to check if a blob exists
        /// </summary>
        public static bool Exists(this CloudBlob blob)
        {
            if (blob == null)
                return false;

            try
            {
                blob.FetchAttributes();
            }
            catch (StorageClientException ex)
            {
                if (ex.StatusCode == HttpStatusCode.NotFound)
                {
                    return false;
                }
            }

            return true;
        }

        /// <summary>
        /// Used to check if a directory exists
        /// </summary>
        public static bool Exists(this CloudBlobDirectory blobDirectory)
        {
            if (blobDirectory == null)
                return false;

            if (blobDirectory.GetFiles().Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
    }
}
